package cc.vv.party.common.ext

import cc.vv.party.beans.vo.OrgVO
import cc.vv.party.common.base.BaseService
import cc.vv.party.common.base.BaseServiceImpl
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.wrapper.PageWrapper
import cc.vv.party.exception.BizException
import com.baomidou.mybatisplus.plugins.Page
import commonx.core.content.transfer
import commonx.core.content.transferEntries

/**
 * @version 1.0.0
 * @author: Gyb
 * @date 2018-10-17
 * @description 项目内扩展方法
 **/

/**
 * mybatis-plus page对象转PageWrapper
 */
inline fun <reified OUT> Page<*>.wrapper(): PageWrapper<OUT> {
    val pageWrapper = this.transfer<PageWrapper<OUT>>()
    pageWrapper.records = records.transferEntries<OUT>() as? MutableList<OUT>
    return pageWrapper
}

fun List<OrgVO>.toTree(): OrgVO {
    val map = this.associateBy { it.id }
    val root: OrgVO? =
        this.find { it.parentId == "0" } ?: throw BizException(StatusCode.ERROR.statusCode, "组织结构数据错误,服务器请排查")
    for (node in this) {
        if (node.parentId == "0") {
            continue
        }
        if (node.parentId == root!!.id) {
            if (root.children == null) {
                root.children = mutableListOf()
            }
            root.children!!.add(node)
        } else {
            val parent = map[node.parentId]
            if (parent!!.children == null) {
                parent.children = mutableListOf()
            }
            parent.children!!.add(node)
        }
    }
    return root!!
}

fun BaseService<*>.uuid(): String {
    return java.util.UUID.randomUUID().toString().replace("-", "")
}